

import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Image, RefreshControl, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface QuickActionItem {
  id: string;
  title: string;
  icon: string;
  color: string;
  onPress: () => void;
}

interface RecentApprovalItem {
  id: string;
  title: string;
  applicant: string;
  status: 'pending' | 'approved' | 'rejected';
  statusText: string;
  time: string;
  processInstanceId: string;
}

interface ApprovalStats {
  total: number;
  completed: number;
  pending: number;
  efficiency: string;
}

const HomeScreen: React.FC = () => {
  const router = useRouter();
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [notificationCount] = useState(3);
  const [pendingCount] = useState(5);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      // 模拟刷新数据
      await new Promise(resolve => setTimeout(resolve, 1000));
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleNotificationPress = () => {
    console.log('需要调用第三方接口实现通知功能');
  };

  const handlePendingReminderPress = () => {
    router.push('/p-pending_approval');
  };

  const handleQuickActionPress = (action: string) => {
    switch (action) {
      case 'pending':
        router.push('/p-pending_approval');
        break;
      case 'approved':
        router.push('/p-approved_by_me');
        break;
      case 'initiated':
        router.push('/p-my_initiated');
        break;
      case 'cc':
        router.push('/p-cc_to_me');
        break;
      case 'statistics':
        router.push('/p-data_statistics');
        break;
      case 'new':
        console.log('需要调用第三方接口实现新建审批功能');
        break;
      case 'templates':
        console.log('需要调用第三方接口实现审批模板功能');
        break;
      case 'more':
        console.log('需要调用第三方接口实现更多功能');
        break;
    }
  };

  const handleRecentApprovalPress = (processInstanceId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${processInstanceId}`);
  };

  const handleViewAllRecentPress = () => {
    router.push('/p-approved_by_me');
  };

  const quickActions: QuickActionItem[] = [
    {
      id: 'pending',
      title: '待我审批',
      icon: 'clock',
      color: '#6366f1',
      onPress: () => handleQuickActionPress('pending'),
    },
    {
      id: 'approved',
      title: '我已审批',
      icon: 'check-circle',
      color: '#10b981',
      onPress: () => handleQuickActionPress('approved'),
    },
    {
      id: 'initiated',
      title: '我发起的',
      icon: 'plus-circle',
      color: '#f59e0b',
      onPress: () => handleQuickActionPress('initiated'),
    },
    {
      id: 'cc',
      title: '抄送我的',
      icon: 'share-alt',
      color: '#06b6d4',
      onPress: () => handleQuickActionPress('cc'),
    },
    {
      id: 'statistics',
      title: '数据统计',
      icon: 'chart-bar',
      color: '#8b5cf6',
      onPress: () => handleQuickActionPress('statistics'),
    },
    {
      id: 'new',
      title: '新建审批',
      icon: 'file-alt',
      color: '#6366f1',
      onPress: () => handleQuickActionPress('new'),
    },
    {
      id: 'templates',
      title: '审批模板',
      icon: 'layer-group',
      color: '#10b981',
      onPress: () => handleQuickActionPress('templates'),
    },
    {
      id: 'more',
      title: '更多',
      icon: 'ellipsis-h',
      color: '#9ca3af',
      onPress: () => handleQuickActionPress('more'),
    },
  ];

  const recentApprovals: RecentApprovalItem[] = [
    {
      id: '1',
      title: '员工请假申请',
      applicant: '李小明',
      status: 'pending',
      statusText: '审批中',
      time: '2小时前',
      processInstanceId: 'PI001',
    },
    {
      id: '2',
      title: '采购申请单',
      applicant: '王采购',
      status: 'approved',
      statusText: '已通过',
      time: '1天前',
      processInstanceId: 'PI002',
    },
    {
      id: '3',
      title: '差旅报销申请',
      applicant: '赵销售',
      status: 'rejected',
      statusText: '已驳回',
      time: '2天前',
      processInstanceId: 'PI003',
    },
  ];

  const approvalStats: ApprovalStats = {
    total: 28,
    completed: 23,
    pending: 5,
    efficiency: '2.5h',
  };

  const getStatusBadgeStyle = (status: string) => {
    switch (status) {
      case 'pending':
        return styles.statusBadgePending;
      case 'approved':
        return styles.statusBadgeApproved;
      case 'rejected':
        return styles.statusBadgeRejected;
      default:
        return styles.statusBadgePending;
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
        }
      >
        {/* 顶部用户信息区域 */}
        <LinearGradient
          colors={['#1f2937', '#111827']}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.userHeader}
        >
          <View style={styles.userInfo}>
            <View style={styles.userDetails}>
              <View style={styles.avatarContainer}>
                <Image
                  source={{
                    uri: 'https://s.coze.cn/image/g3aif_VEvQI/',
                  }}
                  style={styles.userAvatar}
                />
                <View style={styles.onlineIndicator} />
              </View>
              <View style={styles.userTextInfo}>
                <Text style={styles.userName}>张经理</Text>
                <View style={styles.userMeta}>
                  <View style={styles.departmentContainer}>
                    <FontAwesome6
                      name="building"
                      size={12}
                      color="rgba(99, 102, 241, 0.7)"
                    />
                    <Text style={styles.userDepartment}>技术部</Text>
                  </View>
                  <Text style={styles.metaSeparator}>•</Text>
                  <View style={styles.statusContainer}>
                    <View style={styles.statusDot} />
                    <Text style={styles.userStatus}>在线</Text>
                  </View>
                </View>
              </View>
            </View>
            <TouchableOpacity
              style={styles.notificationButton}
              onPress={handleNotificationPress}
            >
              <FontAwesome6 name="bell" size={20} color="#d1d5db" />
              {notificationCount > 0 && (
                <LinearGradient
                  colors={['#ef4444', '#dc2626']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.notificationBadge}
                >
                  <Text style={styles.notificationBadgeText}>
                    {notificationCount}
                  </Text>
                </LinearGradient>
              )}
            </TouchableOpacity>
          </View>
        </LinearGradient>

        {/* 待办提醒区域 */}
        <View style={styles.pendingReminderContainer}>
          <TouchableOpacity
            style={styles.pendingReminder}
            onPress={handlePendingReminderPress}
          >
            <LinearGradient
              colors={['#6366f1', '#8b5cf6']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.pendingReminderGradient}
            >
              <View style={styles.pendingReminderContent}>
                <View style={styles.pendingReminderLeft}>
                  <Text style={styles.pendingTitle}>待我审批</Text>
                  <Text style={styles.pendingCount}>
                    您有 {pendingCount} 项待处理审批
                  </Text>
                </View>
                <View style={styles.pendingReminderRight}>
                  <Text style={styles.pendingNumber}>{pendingCount}</Text>
                  <FontAwesome6
                    name="chevron-right"
                    size={16}
                    color="rgba(255, 255, 255, 0.6)"
                  />
                </View>
              </View>
            </LinearGradient>
          </TouchableOpacity>
        </View>

        {/* 快捷入口区域 */}
        <View style={styles.quickActionsSection}>
          <Text style={styles.sectionTitle}>快捷操作</Text>
          <View style={styles.quickActionsGrid}>
            {quickActions.map((action) => (
              <TouchableOpacity
                key={action.id}
                style={styles.quickActionItem}
                onPress={action.onPress}
                activeOpacity={0.7}
              >
                <LinearGradient
                  colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.quickActionIconContainer}
                >
                  <FontAwesome6
                    name={action.icon}
                    size={24}
                    color={action.color}
                  />
                </LinearGradient>
                <Text style={styles.quickActionTitle}>{action.title}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* 最近审批事项 */}
        <View style={styles.recentApprovalsSection}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>最近审批</Text>
            <TouchableOpacity onPress={handleViewAllRecentPress}>
              <Text style={styles.viewAllButton}>查看全部</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.recentApprovalsList}>
            {recentApprovals.map((item) => (
              <TouchableOpacity
                key={item.id}
                style={styles.recentApprovalItem}
                onPress={() => handleRecentApprovalPress(item.processInstanceId)}
                activeOpacity={0.7}
              >
                <LinearGradient
                  colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.recentApprovalGradient}
                >
                  <View style={styles.recentApprovalHeader}>
                    <Text style={styles.recentApprovalTitle}>{item.title}</Text>
                    <View style={[styles.statusBadge, getStatusBadgeStyle(item.status)]}>
                      <Text style={styles.statusBadgeText}>{item.statusText}</Text>
                    </View>
                  </View>
                  <View style={styles.recentApprovalFooter}>
                    <Text style={styles.applicantText}>申请人：{item.applicant}</Text>
                    <Text style={styles.timeText}>{item.time}</Text>
                  </View>
                </LinearGradient>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        {/* 审批数据概览 */}
        <View style={styles.approvalStatsSection}>
          <Text style={styles.sectionTitle}>本月数据</Text>
          <View style={styles.approvalStatsGrid}>
            <LinearGradient
              colors={['#06b6d4', '#3b82f6']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.statCard}
            >
              <Text style={styles.statNumber}>{approvalStats.total}</Text>
              <Text style={styles.statLabel}>总审批数</Text>
            </LinearGradient>
            <LinearGradient
              colors={['#6366f1', '#8b5cf6']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.statCard}
            >
              <Text style={styles.statNumber}>{approvalStats.completed}</Text>
              <Text style={styles.statLabel}>已完成</Text>
            </LinearGradient>
            <View style={[styles.statCard, styles.statCardPending]}>
              <Text style={[styles.statNumber, styles.statNumberPending]}>
                {approvalStats.pending}
              </Text>
              <Text style={[styles.statLabel, styles.statLabelPending]}>待处理</Text>
            </View>
            <View style={[styles.statCard, styles.statCardEfficiency]}>
              <Text style={[styles.statNumber, styles.statNumberEfficiency]}>
                {approvalStats.efficiency}
              </Text>
              <Text style={[styles.statLabel, styles.statLabelEfficiency]}>平均时长</Text>
            </View>
          </View>
        </View>

        {/* 底部安全区域 */}
        <View style={styles.bottomSafeArea} />
      </ScrollView>
    </SafeAreaView>
  );
};

export default HomeScreen;

